//
//  ZJOAuthViewController.m
//  Weibo29
//
//  Created by 曾静 on 16/6/30.
//  Copyright © 2016年 qq. All rights reserved.
//

#import "ZJOAuthViewController.h"
#import "ZJNetworkTools.h"
#import "ZJUserAccount.h"
@interface ZJOAuthViewController ()<UIWebViewDelegate>


@property (nonatomic, strong)UIWebView *web;

@end

@implementation ZJOAuthViewController

-(UIWebView *)web{
    if (!_web) {
        _web = [[UIWebView alloc]init];
        
        NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",APPKEY,REDIRECT_URI];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        
        [_web loadRequest:request];
        
        _web.delegate = self;
    }
    return _web;
}

-(void)loadView{
   
    
    self.view = self.web;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    
}
//添加nav
-(void)setupNav{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"AOuth登录";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(autofill)];
    
    
    
}

-(void)cancel{
    NSLog(@"取消");
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
-(void)autofill{
    NSLog(@"自动填充");
    //开启js交互
    
    NSString *str = @"document.getElementById('userId').value='13315088145',document.getElementById('passwd').value='a06131024w'";
    
    [self.web stringByEvaluatingJavaScriptFromString:str];
    
}

//实现web的代理方法,在加载请求的相应里面加载
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [SVProgressHUD dismiss];
}
//专门用于js交互的时候拦截数据
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
//    NSLog(@"%@",request);
    
    if ([request.URL.absoluteString hasPrefix:REDIRECT_URI]) {
        //对字符串进行截取
        NSString *str= request.URL.query;
        
        NSString *code = [str substringFromIndex:5];
        
       //获取到了code码
        [self getUserToken:code];
        
    }
    
    return YES;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [SVProgressHUD dismiss];
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
  
    [SVProgressHUD show];
}


-(void)getUserToken:(NSString *)code{
    
    [[ZJNetworkTools shareNetworktools]getUserToken:code andSuccessBlock:^(id result) {
       
        ZJUserAccount *uc = [ZJUserAccount userAccountWithDict:result];
        
        NSLog(@"%@",uc);

        
        
    } andFailBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
@end
